package common;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import model.entity.Product;
import model.exceptions.InvalidNameException;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class PersistenceTest
{

  @BeforeClass
  public static void setUpBeforeClass()
  {
    try
    {
      Files.deleteIfExists(new File("HIT.ser").toPath());
    }
    catch (IOException e)
    {
      System.out.println("File not found.");
    }
  }

  @AfterClass
  public static void tearDownAfterClass()
  {
    try
    {
      Files.deleteIfExists(new File("HIT.ser").toPath());
    }
    catch (IOException e)
    {
      System.out.println("File not found.");
    }
  }

  @Test(expected = InvalidNameException.class)
  public void testLoadEmptyName() throws InvalidNameException, ClassNotFoundException, IOException
  {
    Persistence.load("");
  }

  @Test(expected = InvalidNameException.class)
  public void testLoadNullName() throws InvalidNameException, ClassNotFoundException, IOException
  {
    Persistence.load(null);
  }

  @Test(expected = InvalidNameException.class)
  public void testSaveEmtyName() throws InvalidNameException, ClassNotFoundException, IOException
  {
    Persistence.save(new Object(), "");
  }

  @Test(expected = InvalidNameException.class)
  public void testSaveNullName() throws InvalidNameException, ClassNotFoundException, IOException
  {
    Persistence.save(new Object(), null);
  }

  @Test
  public void testSaveNullObject() throws InvalidNameException, ClassNotFoundException,
      IOException
  {
    Result result = Persistence.save(null, "HIT");
    assertFalse(result.getStatus());
  }

  @Test
  public void testSaveAndLoad() throws InvalidNameException, ClassNotFoundException, IOException
  {
    Product product = new Product("7589234972");
    Result result = Persistence.save(product, "HIT");
    assertTrue(result.getStatus());
    Product foundObject = (Product) Persistence.load("HIT");
    assertNotNull(foundObject);
  }

}
